﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class frm_Edit_PartMistakeReturn : Form
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        public string poid;
        public string orderno;
        public int mistakereturnid = 0;
        public frm_Edit_PartMistakeReturn()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            LoadMistakeList();
            this.orderNo.Properties.AutoComplete = true;
        }

        public void LoadData()
        {
            if (!string.IsNullOrEmpty(orderno) && !string.IsNullOrEmpty(poid))
            {
                try
                {
                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "SELECT * FROM [241_POMistakeReturn] WHERE POID='" + poid + "' AND OrderNo='" + orderno + "'";
                    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                    if (dataReader.Read())
                    {
                        this.returnDate.EditValue = DateTime.Parse(dataReader["InputDate"].ToString());
                        for (int i = 0; i < this.orderNo.Properties.Items.Count; i++)
                        {
                            ComboboxItem item = (ComboboxItem)this.orderNo.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["OrderNo"].ToString())
                            {
                                this.orderNo.SelectedIndex = i;
                            }
                        }
                        this.quantityValue.Text = dataReader["Quantity"].ToString();                        
                    }
                    dataReader.Close();
                    cmd_sql.Dispose();
                    myConnection.Close();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show("Cannot get record of OrderNo " + orderno);
                }
            }
        }
        
        /////////////////////////////////////////////
        /// Load OrderNo and POID from 241_POMistake
        /////////////////////////////////////////////
        private void LoadMistakeList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT DISTINCT OrderNo, POID FROM [241_POMistake] WHERE Quantity>0 ORDER BY OrderNo, POID";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["OrderNo"].ToString();
                    item.Value = dataReader["OrderNo"].ToString();
                    this.orderNo.Properties.Items.Add(item);

                    ComboboxItem item2 = new ComboboxItem();
                    item2.Text = dataReader["POID"].ToString();
                    item2.Value = dataReader["POID"].ToString();
                    this.poID.Properties.Items.Add(item2);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get OrderNo list");
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void orderNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.poID.SelectedIndex = this.orderNo.SelectedIndex;
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            ComboboxItem orderno = (ComboboxItem)orderNo.SelectedItem;
            ComboboxItem poid = (ComboboxItem)poID.SelectedItem;
            DateTime inputdate;
            DateTime.TryParse(returnDate.DateTime.Date.ToString(), out inputdate);
            int totalMistake = RemainMistake(orderno.Value.ToString(), poid.Value.ToString());
            int quantity = Int32.Parse(quantityValue.Text.Trim());
            if (totalMistake <= 0)
            {
                MessageBox.Show("There is no mistake item for Order No: " + orderno.Value.ToString());
            }
            else
            {
                if (quantity > totalMistake)
                {
                    MessageBox.Show("The Order No " + orderno.Value.ToString() + " remain only " + totalMistake + " mistake items.");
                }
                else
                {
                    try
                    {
                        string sql;
                        myConnection.Open();
                        if (mistakereturnid == 0)
                        {
                            sql = "INSERT INTO [241_POMistakeReturn]"
                                + " (InputDate, POID, OrderNo, Quantity)"
                                + " VALUES (@inputdate, '" + poid.Value.ToString() + "', '" + orderno.Value.ToString() + "',"
                                + " " + quantity + ")";
                        }
                        else
                        {
                            sql = "UPDATE [241_POMistakeReturn]"
                                + " SET InputDate=@inputdate, POID='" + poid.Value.ToString() + "',"
                                + " OrderNo='" + orderno.Value.ToString() + "', Quantity=" + quantity
                                + " WHERE ID=" + mistakereturnid;
                        }
                        SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                        cmd_sql.Parameters.Add("@inputdate", SqlDbType.DateTime).Value = inputdate.Date;
                        cmd_sql.ExecuteNonQuery();
                        cmd_sql.Dispose();
                        myConnection.Close();
                        MessageBox.Show("Part Mistake Return updated success.");
                        this.Dispose();
                    }
                    catch
                    {
                        if (myConnection.State == ConnectionState.Open)
                        {
                            myConnection.Close();
                        }
                        MessageBox.Show("Cannot update return mistake");
                    }
                }
            }
        }

        /////////////////////////////////////////
        /// Calculate remain mistake
        /////////////////////////////////////////
        private int RemainMistake(string orderno, string poid)
        {
            int ret = 0;
            int totalmistake = 0;
            int totalreturn = 0;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();

                /// Calculate Total Mistake
                cmd_sql.CommandText = "SELECT SUM(Quantity FROM [241_POMistake] WHERE OrderNo='" + orderno + "' AND POID='" + poid + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    totalmistake = Int32.Parse(dataReader[0].ToString());
                }
                dataReader.Close();

                ///Calculate Total Return
                if (mistakereturnid == 0)
                {
                    cmd_sql.CommandText = "SELECT SUM(Quantity FROM [241_POMistakeReturn]"
                        + " WHERE OrderNo='" + orderno + "' AND POID='" + poid + "'";
                }
                else
                {
                    cmd_sql.CommandText = "SELECT SUM(Quantity FROM [241_POMistakeReturn]"
                        + " WHERE OrderNo='" + orderno + "' AND POID='" + poid + "' AND ID <>" + mistakereturnid;
                }
                dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    totalreturn = Int32.Parse(dataReader[0].ToString());
                }
                dataReader.Close();

                cmd_sql.Dispose();
                myConnection.Close();

                ret = totalmistake - totalreturn;
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Remain Mistake");
            }

            return ret;
        }
    }
}
